<style type="text/css" title="currentStyle">
	@import "../media/css/demo_page.css";
	@import "../media/css/demo_table_jui.css";
	@import "../examples_support/themes/smoothness/jquery-ui-1.8.4.custom.css";
	@import "media/css/TableTools_JUI.css";
</style>
<script type="text/javascript" charset="utf-8" src="../media/js/jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf-8" src="media/js/ZeroClipboard.js"></script>
<script type="text/javascript" charset="utf-8" src="media/js/TableTools.js"></script>
<script type="text/javascript" charset="utf-8">
	$(document).ready( function () {
		$('#example').dataTable( {
			"bJQueryUI": true,
			"sPaginationType": "full_numbers",
			"sDom": 'Tlfrtip',
			"oTableTools": {
				"aButtons": [
					"copy", "csv", "xls", "pdf", "print",
					{
						"sExtends":    "collection",
						"sButtonText": "Save",
						"aButtons":    [ "csv", "xls", "pdf" ]
					}
				]
			}
		} );
	} );
</script>
<?php
@set_time_limit(0);

$fr_hr_selected = 'selected';
$fr_min_selected = 'selected';
$to_hr_selected = 'selected';
$to_min_selected = 'selected';

if(isset($_POST[map_filter_btn]) && $_POST[map_filter_btn]!='')
{
  $fr_hr_selected = '';
  $fr_min_selected = '';
  $to_hr_selected = '';
  $to_min_selected = '';
}
function chk_folder($filename)
{
	$fp_load = @fopen("$filename", "rb");
	if ( $fp_load )
	{
		return true;
	}
	else
	{
		return false;
	}
}

function sec2hms($sec, $padHours=FALSE) {
    $hours_min_secs = "";
    $hours = INTVAL(INTVAL($sec) / 3600); 
    $hours_min_secs .= ($padHours) ? STR_PAD($hours, 2, "0", STR_PAD_LEFT). ':' : $hours. ':';

    $minutes = INTVAL(($sec / 60) % 60); 
   $hours_min_secs .= STR_PAD($minutes, 2, "0", STR_PAD_LEFT). ':';
    $seconds = INTVAL($sec % 60); 
    $hours_min_secs .= STR_PAD($seconds, 2, "0", STR_PAD_LEFT);
    return $hours_min_secs;
}


function getStopReport($sdate,$devName,$devId,$st_time,$en_time,$ent_val_mnt)
{
$cnt = 1;
$tmp=-1;
$t1=0.0;
$t2=0.0;
$timeArr= array();
$timediff=array();
$strTime='';
$endTime='';
$totTime = 0;
$k1 = 0;
$totDist = 0;
	$file = DATAPATH.date("d-m-Y", strtotime($sdate))."/".$devId.".txt";
	//exit;
	if(chk_folder($file))
	{
		$file1 = @fopen($file, "r");
		if($file1)
		{
			while(!feof($file1))
			{
				$data= fgets($file1);
			}
			$data = getSortedData($data);
		}
	
		if(count($data)>0)
		{
		 $data1=explode("#",$data);

		 for($j1=0;$j1<count($data1);$j1++)
		 {
			$data2=explode("@",$data1[$j1]);        

			if(count($data2)>1)
			{
				$data3=explode(",",$data2[1]);
				//echo date("d-m-Y", strtotime($sdate))."==".date("d-m-Y",@mktime(($data3[4]+5),($data3[5]+30),$data3[6],$data3[2],$data3[1],$data3[3]));
				$device=$data3[0];
				$geodate = $data3[8]." ".$data3[9];
				$geoTime = date("H:i:s",strtotime($data3[9]));
				$pos1=calLat($data3[2]);
				$pos2=calLong($data3[1]);
				$curTime = explode(":",date("H:i:s",strtotime($data3[9])));
				$curTime = (($curTime[0]) * 60) + $curTime[1];
				
				if($curTime >= $st_time && $curTime<=$en_time)
				{					
					if($pos1>0 && $pos2>0 )
					{ 
					if(!in_array($geoTime,$timeArr))
					{  
						
						if($$data3[3]==0 && $strTime=='')
						{
							$strTime = $geoTime;
							$pits1 =  $pos1;
							$pits2 =  $pos2;
											
						}
						else if($data3[3] > 9 && $endTime=='' && $strTime!='')
						{ 
							
							$endTime = $geoTime;		
							$diff = strtotime($endTime) - strtotime($strTime);
							if( $diff >= $ent_val_mnt) 
							{
								//echo $endTime." - ".$strTime." ".$diff." ".$ent_val_mnt."<br>";
								//$res2='<a href=http://maps.google.com/maps?q='.$pos1.','.$pos2.' target=_blank title=click here>'.$pos1.','.$pos2.'</a>';
								//$latlngloca = $pos1.','.$pos2;
								$res2 = getMyGeoAddress($pos1,$pos2);
								//echo $res."<br>";
								$totTime += (strtotime($endTime) - strtotime($strTime));
								$finaTime=$strTime."#".$res2."#".$endTime."#".gmdate("H:i:s",(strtotime($endTime) - strtotime($strTime)))."#".$device."#".$devName."#".$totTime.'#'.$sdate."#".$pos1."#".$pos2;
								array_push($timediff, $finaTime);
							}					
							$strTime='';
							$endTime='';
							$diff = '';
						}
						$cnt++; 
						array_push($timeArr,$geoTime);
					}
				}
			}
			}
		}
		if($strTime != "" && $endTime == "")
		{
			//$latlngloca = $pos1.','.$pos2;
			$res2 = getMyGeoAddress($pos1,$pos2);
			$finaTime=$strTime."#".$res2."#".$geoTime."#".gmdate("H:i:s",(strtotime($geoTime) - strtotime($strTime)))."#".$device."#".$devName."#".$totTime.'#'.$sdate."#".$pos1."#".$pos2;
			array_push($timediff, $finaTime);
		}
		fclose($file1);
		}
	}
	
	//echo $strTime." ddd ".$endTime;
	if(count($timediff) > 0)
		return implode("@",$timediff);
	else 
		return "";
}

if($recordUserInfo[ci_clientType] == "Client" && $recordUserInfo[ui_isAdmin] == "1")
{
	$devices_query =  "SELECT * FROM tb_deviceinfo,tb_client_subscription WHERE tcs_isActive = 1 AND tcs_deviceId = di_id AND di_clientId =".$_SESSION[clientID]." AND di_status = 1 ORDER BY di_deviceName,di_deviceId ASC";
}
else if($recordUserInfo[ci_clientType] == "Client" && $recordUserInfo[ui_isAdmin] == "0" && $recordUserInfo[ui_roleId] == "1")
{
	$devices_query = "SELECT * FROM tb_deviceinfo,tb_client_subscription WHERE tcs_isActive = 1 AND tcs_deviceId = di_id AND di_status = 1 AND di_clientId=".$_SESSION[clientID]." AND di_assignedUserId = ".$_SESSION[userID]." ORDER BY di_deviceName,di_deviceId ASC";
}
//echo $devices_query;
//$devices_query =  "SELECT * FROM tb_deviceinfo WHERE di_clientId =".$_SESSION[clientID]." AND di_status = 1 ORDER BY di_deviceName,di_deviceId ASC";
$devices_resp = mysql_query($devices_query);	
?>
<script type="text/javascript" language="javascript">
function showFormDiv()
{
	if(document.getElementById('formDiv').style.display=='none')
	{
		document.getElementById('formDiv').style.display = 'block';
		document.getElementById('shLink').innerHTML = "Hide Form";
	}
	else
	{
		document.getElementById('formDiv').style.display = 'none';
		if(document.getElementById('shLink'))
		document.getElementById('shLink').innerHTML = "Show Form";
	}
}
function showPreloader()
{
	var returnVal = validateMapReport()
	if(returnVal == 1)
	{
		document.getElementById('popup_div').innerHTML = '<div id="loading_txt" >Loading...</div>';
		document.frm_map_filter.submit();
	}
}

function hidePreLoader()
{
	document.getElementById('popup_div').innerHTML = '&nbsp;';
}





function validateMapReport()
{
  if(document.getElementById('map_device_id').value== 0 )
  {
   alert("Select Device"); 
   document.getElementById('map_device_id').focus();
   return 0;  
  }
  
  if(document.getElementById('from_date').value=='')
  { alert("Select From Date"); document.getElementById('from_date').focus();  return 0;  }
  
  if(document.getElementById('to_date').value=='')
  { alert("Select To Date");  document.getElementById('to_date').focus(); return 0; }
  
  
	 var t1=document.getElementById('from_date').value ;
        var t2=document.getElementById('to_date').value;

        var one_day=1000*60*60*24; 
		var x=t1.split("-");     
        var y=t2.split("-");
        var date1=new Date(x[2],(x[1]-1),x[0]);
  
        var date2=new Date(y[2],(y[1]-1),y[0]);
        var month1=x[1]-1;
        var month2=y[1]-1;
        var diff=Math.ceil((date2.getTime()-date1.getTime())/(one_day)); 
         
		 if(diff < 0){
       alert("From Date should be prior to To Date."); document.getElementById('to_date').select();return 0;

		 }
	
	
	return 1;
	
}
jQuery(function() {

//$("#time3, #time4").timePicker();
 $("#time3, #time4").timePicker({
  startTime: "12:01 AM", // Using string. Can take string or Date object.
  endTime: "11:59 PM", // Using Date object here.
  show24Hours: false,
  separator: ':',
  step: 1});    
	
// Store time used by duration.
var oldTime = $.timePicker("#time3").getTime();

// Keep the duration between the two inputs.
$("#time3").change(function() {
  if ($("#time4").val()) { // Only update when second input has a value.
	// Calculate duration.
	var duration = ($.timePicker("#time4").getTime() - oldTime);
	var time = $.timePicker("#time3").getTime();
	// Calculate and update the time in the second input.
	$.timePicker("#time4").setTime(new Date(new Date(time.getTime() + duration)));
	oldTime = time;
  }
});

// Validate.
$("#time4").change(function() {
  if($.timePicker("#time3").getTime() > $.timePicker(this).getTime()) {
	$(this).addClass("error");
  }
  else {
	$(this).removeClass("error");
  }
});

// Validate.
 $("#time5").timePicker({
	  startTime: "00:01", // Using string. Can take string or Date object.
	  endTime: "23:59", // Using Date object here.
	  show24Hours: true,
	  separator: ':',
	  step: 1}); 

});
function sendCSVData()
{
//alert(c1);
document.frmTripData.submit();
//	window.location.href='export.php?csvData='+c1+'&frdate='+c2+'&frtime='+c3+'&totime='+c4+'&vehino='+c5;
	//document.write('export.php?csvData='+c1+'&frdate='+c2+'&frtime='+c3+'&totime='+c4+'&vehino='+c5);
}
$(function() {
	$( "#from_date" ).datepicker({
		changeMonth: true,
		changeYear: true,
		maxDate: 0,
		showOn: "button",
		buttonImage: "images/calendar.gif",
		buttonImageOnly: true,
		dateFormat : "dd-mm-yy"
	});
});
$(function() {
	$( "#to_date" ).datepicker({
		changeMonth: true,
		changeYear: true,
		maxDate: 0,
		showOn: "button",
		buttonImage: "images/calendar.gif",
		buttonImageOnly: true,
		dateFormat : "dd-mm-yy"
	});
});
</script>

<div id="formDiv">
<form id="frm_map_filter" name="frm_map_filter" method="post" action="" onsubmit="return validateMapReport();">      	 
<table class="gridform_final">
<tr><th colspan="9">Stop Report</th></tr>
  <tr>
    <td width="10%" align="right"><span class="form_text">Select Device&nbsp;</span></td>
    <td width="15%" align="left">
        <select name="map_device_id" id="map_device_id" tabindex="1" style="width:90%" onchange="document.frm_map_filter.txtVehicleName.value = this.options[selectedIndex].text">
        <option value="0">Select Device</option>
         <?php 
		while($devices_fetch = @mysql_fetch_assoc($devices_resp)) 
		{ 
			$renewDate = date("d-m-Y",strtotime("-1 days ".$devices_fetch[tcs_renewalDateTo]));
			//echo $date_offline." <= ".date("d-m-Y",strtotime($renewDate))."<br>";
			if(strtotime(date('d-m-Y')) <= strtotime($renewDate))
			{
			if($devices_fetch[di_deviceName])
				$devName = $devices_fetch[di_deviceName];
			else
				$devName = $devices_fetch[di_deviceId];
        ?>
        <option value="<?php echo $devices_fetch[di_deviceId]."#".$devices_fetch[di_imeiId]; ?>" 
        <?php if($_POST[map_device_id] == $devices_fetch[di_deviceId]."#".$devices_fetch[di_imeiId]) echo "selected"; ?>><?php echo $devName; ?></option>
        <?php } } ?>		
        </select>
        <input type="hidden" name="txtVehicleName" id="txtVehicleName" />
        <input type="hidden" name="curdate" id="curdate" value="<?php echo date('Y-m-d'); ?>" />
    </td>
    <td width="20%" align="right"><span class="form_text">From&nbsp;</span>
    <input type="text" name="from_date" id="from_date" readonly="true" size="10" style="width:30%;" tabindex="2" value="<?php if(isset($_POST[from_date])) echo $_POST[from_date]; else echo date("d-m-Y"); ?>" />&nbsp;
    <span><input type="text" name="time3" id="time3" readonly="true" size="7" tabindex="3" value="<?php if($_POST[time3]) echo $_POST[time3]; else echo "12:01 AM";?>" /></span>
    </td>
    <td width="20%" align="right"><span class="form_text">To&nbsp;</span>
    <input type="text" name="to_date" id="to_date" size="12" style="width:30%;" tabindex="4" readonly="true" value="<?php if(isset($_POST[to_date])) echo $_POST[to_date]; else echo date("d-m-Y"); ?>" />&nbsp;
    <span><input type="text" name="time4" id="time4" readonly="true" size="7" tabindex="5" value="<?php if($_POST[time4]) echo $_POST[time4]; else echo "11:59 PM";?>" /></span>
    </td>
    <td align="right" width="20%"><span class="form_text">Overstay Limit</span>
      <span><input type="text" name="time5" id="time5" readonly="true" size="7" tabindex="6" value="<?php if($_POST[time5]) echo $_POST[time5]; else echo "00:01";?>" /></span>(HH:mm)
   
    </td>
    <td width="15%" style="text-align:center">
    <input type="button" name="map_filter_btn"   value="Filter" class="save_btn" tabindex="6"  onclick="showPreloader();"/>
    <input type="hidden" name="map_filter_btn" value="Filter" />
    <input type="button" name="map_cancel_btn" id="map_cancel_btn" value="Reset" class="save_btn" onclick="location.href='index.php?ch=stop';" tabindex="7" /> 
   </td>
  </tr>
</table>
</form>
</div>	
<div id="popup_div" style=" display:block; border:0px;" >

</div>
<?php
if(isset($_POST[map_filter_btn]) && $_POST[map_filter_btn]!='')
{
//print_r($_POST);

$sdate = $_POST[from_date];
$edate = $_POST[to_date];
$srcData = explode("#",$_POST[map_device_id]);

$strtTime = explode(":",date("H:i",strtotime($_POST[time3])));
$strtTime = (($strtTime[0] * 60) + $strtTime[1]);

$endTime = explode(":",date("H:i",strtotime($_POST[time4])));
$endTime = (($endTime[0] * 60) + $endTime[1]);

$ent_val = explode(':',date("H:i",strtotime($_POST[time5])));
$ent_val_mnt = ($ent_val[0]*3600) + ($ent_val[1]*60);

$timediff1=array();
$timediff2=array();
$timediff3=array();
$timediff4=array();
$totalDistance=0;
/*$tripdata = "Date,Start Point,Start Time,End Point,End Time,Duration,Avg. Speed,Dist. Covered";
$tripdata .= "@";*/
$ct=0;
if($_POST[from_date] == $_POST[to_date])
{
	$timediff4 = getStopReport($sdate,$srcData[0],$srcData[1],$strtTime,$endTime,$ent_val_mnt);

}
else
{ 
	$z = GetDays($sdate, $edate);
	
	for($y=0; $y<count($z); $y++)
	{ 
		if($y == 0) 
		{ 
			//$timediff1=getTripReport($z[$y],$srcData[0],$srcData[1],$strtTime,1439,0);
			$res1 = getStopReport($z[$y],$srcData[0],$srcData[1],$strtTime,1439,$ent_val_mnt);
			if($res1)
			$timediff4[] = $res1;
			
		}
		else if($y == count($z)-1) 
		{ 
			$res2 = getStopReport($z[$y],$srcData[0],$srcData[1],$strtTime,$endTime,$ent_val_mnt);;
			if($res2)
			$timediff4[] = $res2;
			
		}
		else if($y < count($z)-1) 
		{ 
			$strtTime1 = 0;
			$endTime1 = 1439;
			$res3 = getStopReport($z[$y],$srcData[0],$srcData[1],0,1439,$ent_val_mnt);;
			if($res3)
			$timediff4[] = $res3;
		
		}
	}
	$timediff4 = implode("@",$timediff4);
}
?>
<table cellpadding="0" cellspacing="0" border="0" class="gridform_final" id="example">      
  <thead>
  <tr>
	    <th width="5%" >#</th>
        <th width="7%">Date</th>
        <th width="10%">Device Name</th>
        <th width="10%">Start Time</th>
        <th width="10%">End Time</th>
        <th>Location</th>
        <th width="10%">Duration</th>
    </tr>
 </thead>
 <tbody>
<?php
	//print_r($timediff4);
	//echo count($timediff4);
	//exit;
	if(count($timediff4) > 0 )
	{
		//print_r($finData);
		$tTdiff1=explode("@",$timediff4);
		for($k=0;$k<count($tTdiff1);$k++)
		{
			$tTdiff = explode("#",$tTdiff1[$k]);
			//print_r($tTdiff);
			$seconds = explode(':',$tTdiff[3]);
			if(!$tTdiff[1])
			{
				$strAddr = getGeocodePOI($tTdiff[8].','.$tTdiff[9]);
			}
			else 
				$strAddr = $tTdiff[1];
		?>		
		 <tr <?php if($r % 2 == 0) { echo 'class="odd_row"';} else { echo 'class="even_row"'; } ?> >
		   <td valign="top"><?php echo $k+1; ?></td>
		   <td valign="top"><?php echo date('d-m-Y',strtotime($tTdiff[7])); ?></td>
		   <td valign="top"><?php echo $_POST[txtVehicleName]; ?></td>
		   <td valign="top"><?php echo date("H:i:s A",strtotime($tTdiff[0])); ?></td>
		   <td valign="top"><?php echo date("H:i:s A",strtotime($tTdiff[2])); ?></td>
		   <td valign="top"><?php echo $strAddr; ?></td>
		   <td valign="top"><?php echo $tTdiff[3]; ?></td>
		 </tr>
		   <?php 
		   $total_s = ($seconds[0]*60*60)+($seconds[2]*60)+($seconds[2]);
		   $total_seconds += $total_s; 		
		   $strAddr1 = '';
		   //exit;
		}  
	}
	?>
<tfoot>
	<tr>
		<td align="right" colspan="7">Total Time :<?php echo sec2hms($total_seconds); ?> </td>
	</tr>
</tfoot>		 
	
</tbody>
</table>
<?php
  
}///end of post

?> 

